import { ICell } from '../../interface';

/**
 * 日期转化为字符串， 4位年+2位月+2位日
 *
 * @param {Date} date
 * @memberof Util
 */
export function getDateStr(date: Date): string {
  const _year = date.getFullYear();
  const _month = date.getMonth() + 1; // 月从0开始计数
  const _day = date.getDate();
  const month = _month > 9 ? '' + _month : '0' + _month;
  const day = _day > 9 ? '' + _day : '0' + _day;
  return _year + month + day;
}

/**
 * 日期转华为标准字符串日期，yyyy-MM-dd
 *
 * @export
 * @param {Date} date
 * @return {*}  {string}
 */
export function getDateStrFull(date: Date): string {
  const _year = date.getFullYear();
  const _month = date.getMonth() + 1; // 月从0开始计数
  const _day = date.getDate();
  const month = _month > 9 ? '' + _month : '0' + _month;
  const day = _day > 9 ? '' + _day : '0' + _day;
  return _year + '-' + month + '-' + day;
}

/**
 * 获取相差天数（单位：天）
 *
 * @static
 * @memberof Util
 */
export function differDateDay(date1: string, date2: string): number {
  const sDate1 = Date.parse(date1);
  const sDate2 = Date.parse(date2);
  let dateSpan = sDate2 - sDate1;
  dateSpan = Math.abs(dateSpan);
  return Math.floor(dateSpan / (24 * 3600 * 1000));
}

/**
 * 生成日期集合
 *
 * @param {Date} currentDate
 * @export
 */
export function generateCells(currentDate: Date, cells: ICell[]) {
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth() + 1;
  const firstDay = new Date(year, month - 1, 1); // 当前月第一天
  cells.forEach((_cell: ICell, index: number) => {
    const thisDay = new Date(year, month - 1, index + 1 - firstDay.getDay());
    const thisDayStr = getDateStr(thisDay);
    const thisDayData = getDateStrFull(thisDay);
    const date = thisDay.getDate();
    const cell: ICell = { value: date < 10 ? '0' + date : date.toString(), class: '', date: thisDayData };
    if (thisDayStr === getDateStr(new Date())) {
      cell.class = 'cell-today';
    } else if (thisDayStr.substr(0, 6) === getDateStr(firstDay).substr(0, 6)) {
      cell.class = 'current-month';
    } else {
      cell.class = 'other-month';
    }
    cells[index] = cell;
  });
  return cells;
}
